import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

function hasUrl(url, next) {
  let result = store.getters.getUser.menus_url.some(item => item == url)
  if (result) {
    next()
  } else {
    next('/home')
  }
}

Vue.use(VueRouter)

export const routersIndex = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title:'菜单管理'
    },
    beforeEnter(to,from,next) {
       hasUrl('/menu',next)
    }
  }, {
    path: '/coss',
    component: () => import('../views/role/coss.vue'),
    meta: {
      title:'角色管理'
    },
    beforeEnter(to,from,next) {
       hasUrl('/menu',next)
    }
  }, {
    path: '/guanli',
    component: () => import('../views/guanliyuan/guanli.vue'),
    meta: {
      title:'管理员管理'
    },
    beforeEnter(to,from,next) {
       hasUrl('/menu',next)
    }
  },{
    path: '/shop',
    component: () => import('../views/shop/shop.vue'),
    meta: {
      title:'商品分类'
    }
  },{
    path: '/spec',
    component: () => import('../views/goodsspec/spec.vue'),
    meta: {
      title:'商品规格'
    }
  },{
    path: '/goods',
    component: () => import('../views/goods/goods.vue'),
    meta: {
      title:'商品管理'
    }
  },{
    path: '/vips',
    component: () => import('../views/vips/vips.vue'),
    meta: {
      title:'会员管理'
    }
  },{
    path: '/banner',
    component: () => import('../views/banner/banner.vue'),
    meta: {
      title:'轮播图管理'
    }
  },{
    path: '/time',
    component: () => import('../views/time/time.vue'),
    meta: {
      title:'秒杀活动'
    }
  }
]

const routes = [
  {
    path: '/login',
    component:()=>import('../pages/login.vue')
  }, {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component:()=>import('../views/home.vue')
      },
      ...routersIndex,
      {
        path: '',
        redirect:'/home'
      }
    ]
  }, {
    path:'*',
    redirect:'/index'
  }
]

const router = new VueRouter({
  routes
})
//调用全局前置路由守卫
router.beforeEach((to,from,next) => {
  if (to.path=='/login') {
    next()
    return
  }
  if (store.getters.getUser) {
    next()
    return
  }
  next('/login')
})

export default router
